package com.pumpkin.web.exception;

import com.pumpkin.web.util.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.thymeleaf.exceptions.TemplateInputException;

import javax.servlet.http.HttpServletRequest;

/**
 * (description)
 *
 * @author jinlong.liao on 2016/6/30
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger LOG = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(value = {Exception.class, TemplateInputException.class})
    public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e) {
        LOG.error("[URL] : {}", req.getRequestURL(), e);

        ModelAndView mav = new ModelAndView(getErrorPageNameByException(e));
        mav.addObject("exception", e.getMessage());
        mav.addObject("url", req.getRequestURL());
        return mav;
    }

    @ExceptionHandler(value = {MinaDataException.class})
    @ResponseBody
    public Result jsonErrorHandler(HttpServletRequest req, Exception e) {
        LOG.error("[URL] : {}", req.getRequestURL(), e);

        Result result = new Result();
        result.setMessage(e.getMessage());
        result.set("url", req.getRequestURL());
        return result;
    }

    private String getErrorPageNameByException(Exception e) {
        if (e instanceof TemplateInputException) {
            return "error/404";
        } else {
            return "error/default";
        }
    }
}
